<template>
  <div class="task-manager">
    <!-- 筛选栏 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="用户ID">
          <el-input-number 
            v-model="filterForm.user_id" 
            :min="1" 
            placeholder="全部" 
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部" clearable style="width: 150px">
            <el-option label="待执行" value="pending" />
            <el-option label="运行中" value="running" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已完成" value="completed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建任务
          </el-button>
          <el-button type="warning" @click="openBacktestDialog">
            策略回测
          </el-button>
          <el-button type="info" @click="openSupportResistanceDialog">
            测试支撑压力位
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="table-card">
      <el-table :data="tasks" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="user_id" label="用户ID" width="100" align="center" />
        <el-table-column prop="name" label="任务名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope?.row?.status)" size="small">
              {{ getStatusText(scope?.row?.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="策略配置" min-width="380">
          <template #default="scope">
            <div class="strategy-info" v-if="scope.row.strategy">
              <el-tag 
                :type="scope.row.strategy.exchange === 'binance' ? 'warning' : ''" 
                size="small"
              >
                {{ scope.row.strategy.exchange === 'binance' ? '币安' : 'OKX' }}
              </el-tag>
              <el-tag 
                :type="scope.row.strategy.strategy_type === 'zone' ? 'success' : 'primary'" 
                size="small"
              >
                {{ scope.row.strategy.strategy_type === 'zone' ? '区间策略' : '指标策略' }}
              </el-tag>
              <el-tag size="small">{{ scope.row.strategy.symbol }}</el-tag>
              <span>金额: {{ scope.row.strategy.amount }}</span>
              <span>K线: {{ scope.row.strategy.interval_minutes }}分钟</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="API配置" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.api_key" type="success" size="small">已配置</el-tag>
            <el-tag v-else type="info" size="small">未配置</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_demo" label="交易环境" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.is_demo === 0 ? 'danger' : 'warning'" size="small">
              {{ scope.row.is_demo === 0 ? '实盘' : '模拟盘' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="last_executed_at" label="最后执行" width="180" align="center">
          <template #default="scope">
            {{ scope.row.last_executed_at ? formatTime(scope.row.last_executed_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'pending' || scope.row.status === 'paused'"
              size="small" 
              type="success"
              @click="handleStart(scope.row.id)"
            >
              启动
            </el-button>
            <el-button 
              v-if="scope.row.status === 'running'"
              size="small" 
              type="warning"
              @click="handlePause(scope.row.id)"
            >
              暂停
            </el-button>
            <el-button 
              size="small" 
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="success"
              @click="handleViewOrders(scope.row)"
            >
              订单
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="taskForm" :rules="formRules" ref="formRef" label-width="120px">
        <!-- 用户ID已自动使用当前登录用户，不需要显示 -->
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-divider content-position="left">策略配置</el-divider>
        <el-form-item label="交易所" prop="strategy.exchange">
          <el-select v-model="taskForm.strategy.exchange" placeholder="请选择交易所" style="width: 100%">
            <el-option label="OKX" value="okx" />
            <el-option label="币安 (Binance)" value="binance" />
          </el-select>
        </el-form-item>
        <el-form-item label="策略类型" prop="strategy.strategy_type">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-radio-group v-model="taskForm.strategy.strategy_type">
              <el-radio value="indicator">指标策略（RSI等）</el-radio>
              <el-radio value="zone">区间策略（支撑压力位）</el-radio>
            </el-radio-group>
            <el-button 
              v-if="taskForm.strategy.strategy_type === 'zone'" 
              type="primary" 
              size="small"
              @click="previewSupportResistance"
              :disabled="!taskForm.strategy.symbol"
            >
              预览支撑压力位
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="币种" prop="strategy.symbol">
          <el-select 
            v-model="taskForm.strategy.symbol" 
            placeholder="请选择币种" 
            filterable
            style="width: 100%"
            :loading="symbolsLoading"
          >
            <el-option
              v-for="item in symbols"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="交易类型" prop="strategy.trade_type">
          <el-radio-group v-model="taskForm.strategy.trade_type">
            <el-radio value="spot">现货交易</el-radio>
            <el-radio value="swap">永续合约</el-radio>
            <el-radio value="futures">交割合约</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item :label="taskForm.strategy.trade_type === 'spot' ? '交易金额(USDT)' : '交易数量(张)'" prop="strategy.amount">
          <el-input-number 
            v-model="taskForm.strategy.amount" 
            :min="0" 
            :precision="2" 
            :step="taskForm.strategy.trade_type === 'spot' ? 10 : 0.1"
            style="width: 100%"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            {{ taskForm.strategy.trade_type === 'spot' ? '现货交易金额（USDT）' : '合约张数（BTC: 1张=0.01币, ETH: 1张=0.1币，支持小数）' }}
          </div>
        </el-form-item>
        
        <!-- 合约专用配置 -->
        <template v-if="taskForm.strategy.trade_type !== 'spot'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="杠杆倍数">
                <el-select v-model="taskForm.strategy.leverage" style="width: 100%">
                  <el-option label="1倍（无杠杆）" value="1" />
                  <el-option label="3倍（保守）" value="3" />
                  <el-option label="5倍（适中）" value="5" />
                  <el-option label="10倍（激进）" value="10" />
                  <el-option label="20倍（高风险）" value="20" />
                  <el-option label="50倍（极高风险）" value="50" />
                  <el-option label="100倍（极限）" value="100" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保证金模式">
                <el-select v-model="taskForm.strategy.trade_mode" style="width: 100%">
                  <el-option label="全仓（共享保证金）" value="cross" />
                  <el-option label="逐仓（独立保证金）" value="isolated" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-alert 
            title="合约交易风险提示" 
            type="warning" 
            :closable="false"
            style="margin-bottom: 15px;"
          >
            <template #default>
              <div style="font-size: 13px; line-height: 1.6;">
                <p style="margin: 0 0 5px 0;">⚠️ 合约交易具有高风险，可能导致本金全部损失</p>
                <p style="margin: 0 0 5px 0;">💡 建议新手从3-5倍杠杆开始，逐步熟悉</p>
                <p style="margin: 0;">🔒 全仓模式：所有仓位共享保证金 | 逐仓模式：每个仓位独立保证金</p>
              </div>
            </template>
          </el-alert>
        </template>
        
        <el-form-item label="K线周期(分钟)" prop="strategy.interval_minutes">
          <el-select 
            v-model="taskForm.strategy.interval_minutes" 
            placeholder="请选择K线周期"
            style="width: 100%"
          >
            <el-option label="1分钟" :value="1" />
            <el-option label="5分钟" :value="5" />
            <el-option label="15分钟" :value="15" />
            <el-option label="30分钟" :value="30" />
            <el-option label="1小时" :value="60" />
            <el-option label="4小时" :value="240" />
            <el-option label="1天" :value="1440" />
          </el-select>
        </el-form-item>
        
        <!-- 动态策略调整配置 -->
        <el-divider content-position="left">动态策略调整（高级）</el-divider>
        
        <el-form-item>
          <template #label>
            <span>启用动态调整</span>
            <el-tooltip 
              content="单边行情时自动调整K线周期和价格间隔，每个条件独立追踪" 
              placement="top"
            >
              <el-icon style="margin-left: 4px"><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-switch 
            v-model="taskForm.strategy.dynamic_adjustment.enabled"
            active-text="开启"
            inactive-text="关闭"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            💡 连续触发N次后，自动切换到更大的K线周期，避免频繁交易
          </div>
        </el-form-item>
        
        <template v-if="taskForm.strategy.dynamic_adjustment.enabled">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="触发次数阈值">
                <el-input-number 
                  v-model="taskForm.strategy.dynamic_adjustment.trigger_count" 
                  :min="2" 
                  :max="10"
                  style="width: 100%"
                />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  连续触发N次后启用动态调整
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="K线周期倍数">
                <el-input-number 
                  v-model="taskForm.strategy.dynamic_adjustment.interval_multiplier" 
                  :min="2" 
                  :max="10"
                  style="width: 100%"
                />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  例如: 5分钟 × 3 = 15分钟
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="价差倍数">
                <el-input-number 
                  v-model="taskForm.strategy.dynamic_adjustment.price_diff_multiplier" 
                  :min="1" 
                  :max="10"
                  style="width: 100%"
                />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  最小价差也会相应调整
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重置时间(分钟)">
                <el-input-number 
                  v-model="taskForm.strategy.dynamic_adjustment.reset_after_minutes" 
                  :min="30" 
                  :max="240"
                  :step="30"
                  style="width: 100%"
                />
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  超过此时间自动重置状态
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-alert 
            title="说明" 
            type="info" 
            :closable="false"
            style="margin-bottom: 15px;"
          >
            <template #default>
              <div style="font-size: 13px; line-height: 1.6;">
                <p style="margin: 0 0 8px 0;">
                  <strong>工作原理：</strong>每个条件独立追踪触发次数
                </p>
                <p style="margin: 0 0 8px 0;">
                  <strong>示例：</strong>买入条件连续触发3次后，自动切换到15分钟K线判断，避免频繁买入
                </p>
                <p style="margin: 0;">
                  <strong>注意：</strong>卖出条件仍使用5分钟K线，互不影响
                </p>
              </div>
            </template>
          </el-alert>
        </template>
        
        <!-- 区间策略专用参数 -->
        <template v-if="taskForm.strategy.strategy_type === 'zone'">
          <el-divider content-position="left">支撑压力位参数</el-divider>
          <el-form-item label="灵敏度">
            <el-slider 
              v-model="taskForm.strategy.sr_sensitivity" 
              :min="0.5" 
              :max="2" 
              :step="0.1"
              :marks="{ 0.5: '保守', 1.0: '标准', 2.0: '宽松' }"
              show-stops
            />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="价格区间数">
                <el-input-number 
                  v-model="taskForm.strategy.sr_num_bins" 
                  :min="20" 
                  :max="100"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最少触及次数">
                <el-input-number 
                  v-model="taskForm.strategy.sr_min_touches" 
                  :min="2" 
                  :max="10"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        
        <el-divider content-position="left">触发条件配置</el-divider>
        
        <!-- 条件列表 -->
        <div v-for="(condition, index) in taskForm.conditions" :key="index" class="condition-item">
          <el-card shadow="hover" style="margin-bottom: 15px;">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>条件 {{ index + 1 }}</span>
                <el-button 
                  type="danger" 
                  size="small" 
                  :icon="Delete"
                  circle
                  @click="removeCondition(index)"
                  v-if="taskForm.conditions.length > 1"
                />
              </div>
            </template>
            
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="指标" :prop="`conditions.${index}.indicator`">
                  <el-select v-model="condition.indicator" placeholder="请选择指标" style="width: 100%">
                    <!-- 指标策略：只显示RSI -->
                    <template v-if="taskForm.strategy.strategy_type === 'indicator'">
                      <el-option label="RSI" value="rsi" />
                    </template>
                    <!-- 区间策略：只显示价格 -->
                    <template v-else-if="taskForm.strategy.strategy_type === 'zone'">
                      <el-option label="价格" value="price" />
                    </template>
                    <!-- 兼容旧数据 -->
                    <template v-else>
                      <el-option label="RSI" value="rsi" />
                      <el-option label="价格" value="price" />
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="关系" :prop="`conditions.${index}.relation`">
                  <el-select v-model="condition.relation" placeholder="请选择关系" style="width: 100%">
                    <!-- 指标策略选项 -->
                    <template v-if="taskForm.strategy.strategy_type === 'indicator'">
                      <el-option label="上穿" value="crossover" />
                      <el-option label="下穿" value="crossunder" />
                      <el-option label="大于" value="greater_than" />
                      <el-option label="小于" value="less_than" />
                    </template>
                    <!-- 区间策略选项 -->
                    <template v-else-if="taskForm.strategy.strategy_type === 'zone'">
                      <el-option label="接近支撑位" value="near_support" />
                      <el-option label="接近压力位" value="near_resistance" />
                      <el-option label="跌破支撑位（买入）" value="break_below_support" />
                      <el-option label="突破压力位（卖出）" value="break_above_resistance" />
                    </template>
                    <!-- 兼容旧数据：显示所有选项 -->
                    <template v-else>
                      <el-option label="上穿" value="crossover" />
                      <el-option label="下穿" value="crossunder" />
                      <el-option label="大于" value="greater_than" />
                      <el-option label="小于" value="less_than" />
                      <el-option label="接近支撑位" value="near_support" />
                      <el-option label="接近压力位" value="near_resistance" />
                      <el-option label="跌破支撑位" value="break_below_support" />
                      <el-option label="突破压力位" value="break_above_resistance" />
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item :prop="`conditions.${index}.value`">
                  <template #label>
                    <span>目标值</span>
                    <el-tooltip 
                      v-if="['near_support', 'near_resistance', 'break_below_support', 'break_above_resistance'].includes(condition.relation)"
                      content="支撑压力位策略：填写容忍度，如0.01表示1%范围内" 
                      placement="top"
                    >
                      <el-icon style="margin-left: 4px"><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </template>
                  <el-input-number 
                    v-model="condition.value" 
                    :min="0" 
                    :max="100" 
                    :step="condition.relation.includes('support') || condition.relation.includes('resistance') ? 0.01 : 1"
                    :precision="condition.relation.includes('support') || condition.relation.includes('resistance') ? 2 : 0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="动作" :prop="`conditions.${index}.action`">
                  <el-select v-model="condition.action" placeholder="请选择动作" style="width: 100%">
                    <!-- 现货交易动作 -->
                    <template v-if="taskForm.strategy.trade_type === 'spot'">
                      <el-option label="买入" value="buy" />
                      <el-option label="卖出" value="sell" />
                    </template>
                    <!-- 合约交易动作 -->
                    <template v-else>
                      <el-option label="开多（做多）" value="open_long" />
                      <el-option label="开空（做空）" value="open_short" />
                      <el-option label="平多（平掉多单）" value="close_long" />
                      <el-option label="平空（平掉空单）" value="close_short" />
                      <el-option label="平仓（平掉所有持仓）" value="close_position" />
                    </template>
                  </el-select>
                  <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                    <template v-if="taskForm.strategy.trade_type !== 'spot'">
                      💡 开多=看涨买入 | 开空=看跌卖出 | 平仓=关闭持仓
                    </template>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="触发间隔(分钟)" :prop="`conditions.${index}.trigger_interval_minutes`">
              <el-select 
                v-model="condition.trigger_interval_minutes" 
                placeholder="请选择触发间隔"
                style="width: 100%"
              >
                <el-option label="1分钟" :value="1" />
                <el-option label="5分钟" :value="5" />
                <el-option label="10分钟" :value="10" />
                <el-option label="15分钟" :value="15" />
                <el-option label="30分钟" :value="30" />
                <el-option label="1小时" :value="60" />
                <el-option label="2小时" :value="120" />
                <el-option label="4小时" :value="240" />
              </el-select>
            </el-form-item>
            
            <!-- 最小价差配置（仅买入动作显示） -->
            <el-form-item 
              v-if="condition.action === 'buy'" 
              label="最小价差(USDT)" 
              :prop="`conditions.${index}.min_price_diff`"
            >
              <el-input-number
                v-model="condition.min_price_diff"
                :min="0"
                :step="0.1"
                :precision="2"
                placeholder="不填或0则不检查价差"
                style="width: 100%"
              />
              <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                当前价格与上次买入价格的差值必须大于此值才触发买入，避免价格变化不大时重复买入
              </div>
            </el-form-item>
          </el-card>
        </div>
        
        <el-button type="primary" :icon="Plus" @click="addCondition" style="width: 100%; margin-bottom: 15px;">
          添加条件
        </el-button>
        <el-divider content-position="left">API配置</el-divider>
        <el-form-item label="API Key">
          <el-input v-model="taskForm.api_key" placeholder="请输入OKX API Key（可选）" show-password />
        </el-form-item>
        <el-form-item label="API Secret">
          <el-input v-model="taskForm.api_secret" placeholder="请输入OKX API Secret（可选）" show-password />
        </el-form-item>
        <el-form-item label="Passphrase">
          <el-input v-model="taskForm.passphrase" placeholder="请输入OKX Passphrase（可选）" show-password />
        </el-form-item>
        <el-form-item label="交易环境">
          <el-radio-group v-model="taskForm.is_demo">
            <el-radio :label="1">模拟盘</el-radio>
            <el-radio :label="0">实盘</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="left">邮件通知</el-divider>
        <el-form-item label="通知邮箱">
          <el-input 
            v-model="taskForm.notification_email" 
            placeholder="请输入邮箱地址，交易成功后将发送通知（可选）"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            💡 提示：需要先在邮件配置页面配置发件邮箱
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 回测对话框 -->
    <el-dialog 
      v-model="backtestDialogVisible" 
      title="策略回测" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="backtestParams" label-width="140px">
        <el-form-item label="交易对">
          <el-select 
            v-model="backtestParams.symbol" 
            placeholder="请选择币种" 
            filterable
            style="width: 100%"
            :loading="symbolsLoading"
          >
            <el-option 
              v-for="item in symbols" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="K线周期">
          <el-select v-model="backtestParams.interval" placeholder="请选择K线周期" style="width: 100%">
            <el-option label="1分钟" value="1m" />
            <el-option label="5分钟" value="5m" />
            <el-option label="15分钟" value="15m" />
            <el-option label="30分钟" value="30m" />
            <el-option label="1小时" value="1H" />
            <el-option label="4小时" value="4H" />
            <el-option label="1天" value="1D" />
          </el-select>
        </el-form-item>
        <el-form-item label="初始资金(USDT)">
          <el-input-number v-model="backtestParams.initial_capital" :min="100" :step="100" />
        </el-form-item>
        <el-form-item label="单次交易金额(USDT)">
          <el-input-number v-model="backtestParams.trade_amount" :min="10" :step="10" />
        </el-form-item>
        <el-form-item label="策略类型">
          <el-select v-model="backtestParams.strategy_type" placeholder="请选择策略类型" style="width: 100%">
            <el-option label="指标策略 (RSI)" value="indicator" />
            <el-option label="趋势反转策略" value="trend_reversal" />
          </el-select>
        </el-form-item>
        
        <!-- 指标策略参数 -->
        <template v-if="backtestParams.strategy_type === 'indicator'">
          <el-form-item label="RSI买入阈值">
            <el-input-number v-model="backtestParams.rsi_buy_threshold" :min="0" :max="100" />
          </el-form-item>
          <el-form-item label="RSI卖出阈值">
            <el-input-number v-model="backtestParams.rsi_sell_threshold" :min="0" :max="100" />
          </el-form-item>
        </template>
        
        <!-- 趋势反转策略参数 -->
        <template v-if="backtestParams.strategy_type === 'trend_reversal'">
          <el-form-item label="置信度阈值">
            <el-input-number v-model="backtestParams.reversal_confidence" :min="0" :max="100" :step="5" />
            <span style="margin-left: 10px; color: #909399; font-size: 12px">
              至少2个信号确认，置信度>=阈值时触发交易
            </span>
          </el-form-item>
        </template>
        
        <el-form-item label="RSI周期">
          <el-input-number v-model="backtestParams.rsi_period" :min="5" :max="30" />
        </el-form-item>
      </el-form>

      <!-- 回测结果 -->
      <el-card v-if="backtestResult" class="backtest-result" shadow="never">
        <template #header>
          <div class="card-header">
            <span>回测结果</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="策略类型" :span="2">
            <el-tag :type="backtestResult.strategy_type === 'trend_reversal' ? 'warning' : 'primary'">
              {{ backtestResult.strategy_type === 'trend_reversal' ? '趋势反转策略' : '指标策略' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="初始资金">
            {{ backtestResult.initial_capital.toFixed(2) }} USDT
          </el-descriptions-item>
          <el-descriptions-item label="最终资金">
            <span :class="backtestResult.profit >= 0 ? 'profit' : 'loss'">
              {{ backtestResult.final_capital.toFixed(2) }} USDT
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="收益金额">
            <span :class="backtestResult.profit >= 0 ? 'profit' : 'loss'">
              {{ backtestResult.profit >= 0 ? '+' : '' }}{{ backtestResult.profit.toFixed(2) }} USDT
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="收益率">
            <span :class="backtestResult.return_rate >= 0 ? 'profit' : 'loss'">
              {{ backtestResult.return_rate >= 0 ? '+' : '' }}{{ backtestResult.return_rate.toFixed(2) }}%
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="剩余现金">
            {{ backtestResult.cash.toFixed(2) }} USDT
          </el-descriptions-item>
          <el-descriptions-item label="持仓市值">
            {{ backtestResult.position_value.toFixed(2) }} USDT
          </el-descriptions-item>
          <el-descriptions-item label="总交易次数">
            {{ backtestResult.total_trades }}
          </el-descriptions-item>
          <el-descriptions-item label="买入/卖出">
            {{ backtestResult.buy_count }} / {{ backtestResult.sell_count }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间" :span="2">
            {{ backtestResult.start_time }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间" :span="2">
            {{ backtestResult.end_time }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 交易记录 -->
        <el-divider content-position="left">交易记录 (最近10条)</el-divider>
        <el-table :data="backtestResult.trades.slice(-10).reverse()" size="small" max-height="300">
          <el-table-column prop="timestamp" label="时间" width="180">
            <template #default="scope">
              {{ new Date(scope.row.timestamp).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="80" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.type === 'buy' ? 'success' : 'danger'" size="small">
                {{ scope.row.type === 'buy' ? '买入' : '卖出' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="120" align="right">
            <template #default="scope">
              {{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="120" align="right">
            <template #default="scope">
              {{ scope.row.quantity.toFixed(6) }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="120" align="right">
            <template #default="scope">
              {{ scope.row.amount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="rsi" label="RSI" width="80" align="right">
            <template #default="scope">
              {{ scope.row.rsi.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="signal" label="信号" width="120" align="center" v-if="backtestResult.strategy_type === 'trend_reversal'">
            <template #default="scope">
              <el-tag v-if="scope.row.signal" :type="scope.row.signal === 'bullish_reversal' ? 'success' : 'danger'" size="small">
                {{ scope.row.signal === 'bullish_reversal' ? '看涨反转' : '看跌反转' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="confidence" label="置信度" width="80" align="right" v-if="backtestResult.strategy_type === 'trend_reversal'">
            <template #default="scope">
              {{ scope.row.confidence ? scope.row.confidence.toFixed(0) + '%' : '-' }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <template #footer>
        <el-button @click="backtestDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="runBacktestAction" :loading="backtestLoading">
          {{ backtestResult ? '重新回测' : '开始回测' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 支撑压力位测试对话框 -->
    <el-dialog 
      v-model="srDialogVisible" 
      title="支撑压力位计算" 
      width="900px"
      :close-on-click-modal="false"
    >
      <el-alert 
        v-if="srResult" 
        title="预览模式：这是根据最近100根K线计算的支撑压力位，仅供参考" 
        type="info" 
        :closable="false"
        style="margin-bottom: 15px;"
      />
      <el-form :model="srParams" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交易对">
              <el-select 
                v-model="srParams.symbol" 
                placeholder="请选择币种" 
                filterable
                style="width: 100%"
                :loading="symbolsLoading"
              >
                <el-option 
                  v-for="symbol in symbols" 
                  :key="symbol.instId" 
                  :label="symbol.instId" 
                  :value="symbol.instId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="K线周期">
              <el-select v-model="srParams.interval" placeholder="请选择K线周期" style="width: 100%">
                <el-option label="1分钟" value="1m" />
                <el-option label="5分钟" value="5m" />
                <el-option label="15分钟" value="15m" />
                <el-option label="30分钟" value="30m" />
                <el-option label="1小时" value="1H" />
                <el-option label="4小时" value="4H" />
                <el-option label="1天" value="1D" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格区间数">
              <el-input-number v-model="srParams.num_bins" :min="20" :max="100" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最少触及次数">
              <el-input-number v-model="srParams.min_touches" :min="2" :max="10" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="聚类容忍度(%)">
              <el-input-number v-model="srParams.cluster_tolerance" :min="0.1" :max="2" :step="0.1" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="灵敏度">
              <el-slider 
                v-model="srParams.sensitivity" 
                :min="0.5" 
                :max="2" 
                :step="0.1" 
                :marks="{ 0.5: '保守', 1.0: '标准', 1.5: '宽松', 2.0: '很宽松' }"
                show-stops
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 结果展示 -->
      <el-card v-if="srResult" class="sr-result" shadow="never">
        <template #header>
          <div class="card-header">
            <span>识别结果</span>
            <el-tag type="info" size="small">当前价格: {{ srResult.current_price.toFixed(2) }}</el-tag>
          </div>
        </template>
        
        <el-row :gutter="20">
          <!-- 支撑位 -->
          <el-col :span="12">
            <h4>支撑位 ({{ srResult.support_levels.length }}个)</h4>
            <el-table :data="srResult.support_levels" border size="small" max-height="300">
              <el-table-column label="价格区间" align="center" width="180">
                <template #default="scope">
                  <div style="display: flex; flex-direction: column; gap: 4px;">
                    <span class="support-price" style="font-weight: bold;">{{ scope.row.price.toFixed(2) }}</span>
                    <span style="font-size: 11px; color: #909399;">
                      {{ scope.row.zone_low.toFixed(2) }} ~ {{ scope.row.zone_high.toFixed(2) }}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="触及次数" prop="touches" align="center" width="100" />
              <el-table-column label="强度" align="center">
                <template #default="scope">
                  <el-progress 
                    :percentage="(scope.row.strength * 100).toFixed(0)" 
                    :color="'#67c23a'"
                    :show-text="true"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>

          <!-- 压力位 -->
          <el-col :span="12">
            <h4>压力位 ({{ srResult.resistance_levels.length }}个)</h4>
            <el-table :data="srResult.resistance_levels" border size="small" max-height="300">
              <el-table-column label="价格区间" align="center" width="180">
                <template #default="scope">
                  <div style="display: flex; flex-direction: column; gap: 4px;">
                    <span class="resistance-price" style="font-weight: bold;">{{ scope.row.price.toFixed(2) }}</span>
                    <span style="font-size: 11px; color: #909399;">
                      {{ scope.row.zone_low.toFixed(2) }} ~ {{ scope.row.zone_high.toFixed(2) }}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="触及次数" prop="touches" align="center" width="100" />
              <el-table-column label="强度" align="center">
                <template #default="scope">
                  <el-progress 
                    :percentage="(scope.row.strength * 100).toFixed(0)" 
                    :color="'#f56c6c'"
                    :show-text="true"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-card>

      <template #footer>
        <el-button @click="srDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="calculateSupportResistance" :loading="srLoading">
          {{ srResult ? '重新计算' : '开始计算' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 订单查询对话框 -->
    <el-dialog 
      v-model="ordersDialogVisible" 
      :title="`任务订单 - ${currentTaskName}`" 
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-alert 
        v-if="ordersData"
        :title="`总收益: ${ordersData.statistics.total_profit >= 0 ? '+' : ''}${ordersData.statistics.total_profit} USDT (${ordersData.statistics.profit_rate >= 0 ? '+' : ''}${ordersData.statistics.profit_rate}%)`"
        :type="ordersData.statistics.total_profit >= 0 ? 'success' : 'error'"
        :closable="false"
        style="margin-bottom: 20px; font-size: 16px; font-weight: bold;"
      />

      <!-- 统计信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;" v-if="ordersData">
        <el-col :span="6">
          <el-statistic title="总订单数" :value="ordersData.statistics.total_orders" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="买入次数" :value="ordersData.statistics.buy_count" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="卖出次数" :value="ordersData.statistics.sell_count" />
        </el-col>
        <el-col :span="6">
          <el-statistic 
            title="收益率" 
            :value="ordersData.statistics.profit_rate" 
            suffix="%"
            :value-style="{ color: ordersData.statistics.profit_rate >= 0 ? '#67c23a' : '#f56c6c' }"
          />
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-bottom: 20px;" v-if="ordersData">
        <el-col :span="8">
          <el-statistic title="总买入金额" :value="ordersData.statistics.total_buy_amount" suffix="USDT" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="总卖出金额" :value="ordersData.statistics.total_sell_amount" suffix="USDT" />
        </el-col>
        <el-col :span="8">
          <el-statistic 
            title="总收益" 
            :value="ordersData.statistics.total_profit" 
            suffix="USDT"
            :value-style="{ color: ordersData.statistics.total_profit >= 0 ? '#67c23a' : '#f56c6c' }"
          />
        </el-col>
      </el-row>

      <!-- 订单列表 -->
      <el-table 
        v-loading="ordersLoading"
        :data="ordersData?.orders || []" 
        border 
        stripe
        max-height="400"
      >
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getActionTagType(scope.row.type)" size="small">
              {{ getActionText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="symbol" label="交易对" width="120" align="center" />
        <el-table-column prop="exchange" label="交易所" width="80" align="center" />
        <el-table-column prop="amount" label="金额(USDT)" width="120" align="right">
          <template #default="scope">
            {{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="filled_size" label="数量" width="120" align="right">
          <template #default="scope">
            {{ scope.row.filled_size.toFixed(6) }}
          </template>
        </el-table-column>
        <el-table-column prop="avg_price" label="成交均价" width="120" align="right">
          <template #default="scope">
            {{ scope.row.avg_price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="trigger_rsi" label="触发RSI" width="90" align="right">
          <template #default="scope">
            {{ scope.row.trigger_rsi ? scope.row.trigger_rsi.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="completed_at" label="完成时间" width="180">
          <template #default="scope">
            {{ scope.row.completed_at ? new Date(scope.row.completed_at).toLocaleString() : '-' }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="ordersDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Delete, QuestionFilled } from '@element-plus/icons-vue'
import * as tasksApi from '../api/tasks.js'
import { getSymbols } from '../api/okx.js'
import { runBacktest } from '../api/backtest.js'
import { API_BASE_URL } from '../api/config.js'

// 数据
const tasks = ref([])
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const editingTaskId = ref(null)
const formRef = ref(null)
const symbols = ref([]) // 币种列表
const symbolsLoading = ref(false) // 币种加载状态
const currentUser = ref(null) // 当前登录用户

// 订单查询相关
const ordersDialogVisible = ref(false)
const ordersLoading = ref(false)
const ordersData = ref(null)
const currentTaskName = ref('')

// 回测相关
const backtestDialogVisible = ref(false)
const backtestLoading = ref(false)
const backtestResult = ref(null)
const backtestParams = reactive({
  exchange: 'okx',
  symbol: 'BTC-USDT',
  interval: '5m',
  initial_capital: 1000,
  trade_amount: 100,
  strategy_type: 'trend_reversal',  // 默认使用趋势反转策略
  rsi_buy_threshold: 28,
  rsi_sell_threshold: 70,
  rsi_period: 14,
  reversal_confidence: 60  // 趋势反转置信度阈值
})

// 筛选表单
const filterForm = reactive({
  user_id: null,
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 任务表单
const taskForm = ref({
  user_id: 1,
  name: '',
  strategy: {
    exchange: 'okx',  // 默认OKX
    amount: 100.0,
    interval_minutes: 5,
    symbol: 'BTC-USDT',
    strategy_type: 'indicator',  // 默认为指标策略
    trade_type: 'spot',  // 交易类型：spot(现货), swap(永续合约), futures(交割合约)
    leverage: '1',  // 杠杆倍数（仅合约）
    trade_mode: 'cross',  // 保证金模式：cross(全仓), isolated(逐仓)
    sr_sensitivity: 1.0,  // 支撑压力位灵敏度
    sr_num_bins: 50,  // 价格区间数
    sr_min_touches: 3,  // 最少触及次数
    // 动态调整配置
    dynamic_adjustment: {
      enabled: false,
      trigger_count: 3,
      interval_multiplier: 3,
      price_diff_multiplier: 2,
      reset_after_minutes: 60
    }
  },
  conditions: [
    {
      indicator: 'rsi',
      relation: 'crossunder',
      value: 30,
      action: 'buy',
      trigger_interval_minutes: 10
    }
  ],
  api_key: '',
  api_secret: '',
  passphrase: '',
  is_demo: 1,
  notification_email: ''
})

// 表单验证规则
const formRules = {
  user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  'strategy.symbol': [{ required: true, message: '请选择币种', trigger: 'change' }],
  'strategy.amount': [{ required: true, message: '请输入交易金额', trigger: 'blur' }],
  'strategy.interval_minutes': [{ required: true, message: '请选择K线周期', trigger: 'change' }]
}

// 对话框标题
const dialogTitle = ref('创建任务')

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true
  try {
    const params = {
      skip: (pagination.page - 1) * pagination.pageSize,
      limit: pagination.pageSize
    }
    
    if (filterForm.user_id) {
      params.user_id = filterForm.user_id
    }
    if (filterForm.status) {
      params.status = filterForm.status
    }

    console.log('📤 请求参数:', params)
    const data = await tasksApi.getTasks(params)
    console.log('📥 返回数据:', data)
    console.log('📊 数据类型:', typeof data, Array.isArray(data))
    
    tasks.value = data
    // 注意：后端需要返回总数，这里暂时用数组长度
    pagination.total = data.length
    
    console.log('✅ 任务列表更新完成，共', data.length, '条')
  } catch (error) {
    console.error('❌ 获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败: ' + error.message)
    tasks.value = [] // 确保失败时也是空数组
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.page = 1
  fetchTasks()
}

// 重置
const handleReset = () => {
  filterForm.user_id = null
  filterForm.status = ''
  pagination.page = 1
  fetchTasks()
}

// 添加条件
const addCondition = () => {
  taskForm.value.conditions.push({
    indicator: 'rsi',
    relation: 'crossover',
    value: 70,
    action: 'sell',
    trigger_interval_minutes: 10
  })
}

// 删除条件
const removeCondition = (index) => {
  taskForm.value.conditions.splice(index, 1)
}

// 创建任务
const handleCreate = () => {
  isEdit.value = false
  dialogTitle.value = '创建任务'
  taskForm.value = {
    user_id: currentUser.value?.id || 1,  // 使用当前登录用户ID
    name: '',
    strategy: {
      exchange: 'okx',  // 默认OKX
      amount: 100.0,
      interval_minutes: 5,
      symbol: 'BTC-USDT',
      strategy_type: 'indicator',  // 默认为指标策略
      trade_type: 'spot',  // 默认现货交易
      leverage: '1',  // 默认1倍杠杆
      trade_mode: 'cross',  // 默认全仓
      sr_sensitivity: 1.0,
      sr_num_bins: 50,
      sr_min_touches: 3,
      // 动态调整配置
      dynamic_adjustment: {
        enabled: false,
        trigger_count: 3,
        interval_multiplier: 3,
        price_diff_multiplier: 2,
        reset_after_minutes: 60
      }
    },
    conditions: [
      {
        indicator: 'rsi',
        relation: 'crossunder',
        value: 30,
        action: 'buy',
        trigger_interval_minutes: 10
      }
    ],
    api_key: '',
    api_secret: '',
    passphrase: '',
    is_demo: 1,
    notification_email: ''
  }
  dialogVisible.value = true
}

// 编辑任务
const handleEdit = (row) => {
  isEdit.value = true
  editingTaskId.value = row.id
  dialogTitle.value = '编辑任务'
  taskForm.value = {
    user_id: row.user_id,
    name: row.name,
    strategy: {
      ...row.strategy,
      // 兼容旧数据：如果没有这些字段，使用默认值
      trade_type: row.strategy.trade_type || 'spot',
      leverage: row.strategy.leverage || '1',
      trade_mode: row.strategy.trade_mode || 'cross',
      // 兼容旧数据：补充动态调整配置
      dynamic_adjustment: row.strategy.dynamic_adjustment || {
        enabled: false,
        trigger_count: 3,
        interval_multiplier: 3,
        price_diff_multiplier: 2,
        reset_after_minutes: 60
      },
      // 兼容旧数据：补充区间策略参数
      sr_sensitivity: row.strategy.sr_sensitivity || 1.0,
      sr_num_bins: row.strategy.sr_num_bins || 50,
      sr_min_touches: row.strategy.sr_min_touches || 3
    },
    conditions: row.conditions ? [...row.conditions] : [],
    api_key: row.api_key || '',
    api_secret: row.api_secret || '',
    passphrase: row.passphrase || '',
    is_demo: row.is_demo ?? 1,
    notification_email: row.notification_email || ''
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      if (isEdit.value) {
        // 更新任务
        await tasksApi.updateTask(editingTaskId.value, taskForm.value)
        ElMessage.success('任务更新成功')
      } else {
        // 创建任务
        await tasksApi.createTask(taskForm.value)
        ElMessage.success('任务创建成功')
      }
      dialogVisible.value = false
      fetchTasks()
    } catch (error) {
      ElMessage.error((isEdit.value ? '更新' : '创建') + '任务失败: ' + error.message)
    } finally {
      submitting.value = false
    }
  })
}

// 启动任务
const handleStart = async (taskId) => {
  try {
    await tasksApi.startTask(taskId)
    ElMessage.success('任务已启动')
    fetchTasks()
  } catch (error) {
    ElMessage.error('启动任务失败: ' + error.message)
  }
}

// 暂停任务
const handlePause = async (taskId) => {
  try {
    await tasksApi.pauseTask(taskId)
    ElMessage.success('任务已暂停')
    fetchTasks()
  } catch (error) {
    ElMessage.error('暂停任务失败: ' + error.message)
  }
}

// 查看任务订单
const handleViewOrders = async (task) => {
  currentTaskName.value = task.name
  ordersDialogVisible.value = true
  ordersLoading.value = true
  ordersData.value = null
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/tasks/${task.id}/orders`)
    const data = await response.json()
    
    if (response.ok) {
      ordersData.value = data
      ElMessage.success('订单数据加载成功')
    } else {
      ElMessage.error(data.detail || '获取订单失败')
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    ElMessage.error('获取订单失败: ' + error.message)
  } finally {
    ordersLoading.value = false
  }
}

// 打开回测对话框
const openBacktestDialog = () => {
  // 重置参数为默认值
  backtestParams.exchange = 'okx'
  backtestParams.symbol = 'BTC-USDT'
  backtestParams.interval = '5m'
  backtestParams.initial_capital = 1000
  backtestParams.trade_amount = 100
  backtestParams.strategy_type = 'trend_reversal'
  backtestParams.rsi_buy_threshold = 28
  backtestParams.rsi_sell_threshold = 70
  backtestParams.rsi_period = 14
  backtestParams.reversal_confidence = 60
  
  // 重置结果
  backtestResult.value = null
  
  // 加载交易对列表
  fetchSymbols()
  
  // 显示对话框
  backtestDialogVisible.value = true
}

// 执行回测
const runBacktestAction = async () => {
  backtestLoading.value = true
  try {
    const response = await runBacktest(backtestParams)
    
    if (response.code === '0') {
      backtestResult.value = response.data
      ElMessage.success('回测完成')
    } else {
      ElMessage.error(response.msg || '回测失败')
    }
  } catch (error) {
    console.error('回测失败:', error)
    ElMessage.error('回测失败: ' + (error.message || '未知错误'))
  } finally {
    backtestLoading.value = false
  }
}

// 支撑压力位相关
const srDialogVisible = ref(false)
const srLoading = ref(false)
const srResult = ref(null)
const srParams = reactive({
  symbol: 'ETH-USDT',
  interval: '5m',
  num_bins: 50,
  min_touches: 3,
  cluster_tolerance: 0.5,  // 前端显示为百分比
  sensitivity: 1.0  // 灵敏度
})

// 预览支撑压力位（从任务表单）
const previewSupportResistance = async () => {
  if (!taskForm.value.strategy.symbol) {
    ElMessage.warning('请先选择币种')
    return
  }
  
  // 使用任务表单中的币种和K线周期
  srParams.symbol = taskForm.value.strategy.symbol
  srParams.interval = `${taskForm.value.strategy.interval_minutes}m`
  srParams.num_bins = 50
  srParams.min_touches = 3
  srParams.cluster_tolerance = 0.5
  srParams.sensitivity = 1.0
  
  // 打开对话框
  srDialogVisible.value = true
  
  // 自动计算
  await calculateSupportResistance()
}

// 打开支撑压力位对话框
const openSupportResistanceDialog = () => {
  srParams.symbol = 'ETH-USDT'
  srParams.interval = '5m'
  srParams.num_bins = 50
  srParams.min_touches = 3
  srParams.cluster_tolerance = 0.5
  srParams.sensitivity = 1.0
  srResult.value = null
  srDialogVisible.value = true
}

// 计算支撑压力位
const calculateSupportResistance = async () => {
  srLoading.value = true
  try {
    const response = await fetch(`${API_BASE_URL}/api/indicators/support-resistance`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        symbol: srParams.symbol,
        interval: srParams.interval,
        num_bins: srParams.num_bins,
        min_touches: srParams.min_touches,
        cluster_tolerance: srParams.cluster_tolerance / 100,  // 转换为小数
        sensitivity: srParams.sensitivity
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      srResult.value = data
      ElMessage.success('计算完成')
    } else {
      ElMessage.error(data.detail || '计算失败')
    }
  } catch (error) {
    console.error('计算支撑压力位失败:', error)
    ElMessage.error('计算失败: ' + (error.message || '未知错误'))
  } finally {
    srLoading.value = false
  }
}

// 删除任务
const handleDelete = async (taskId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await tasksApi.deleteTask(taskId)
    ElMessage.success('任务已删除')
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败: ' + error.message)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchTasks()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchTasks()
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'info',
    running: 'success',
    paused: 'warning',
    completed: '',
    failed: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待执行',
    running: '运行中',
    paused: '已暂停',
    completed: '已完成',
    failed: '失败'
  }
  return texts[status] || status
}

// 获取动作文本（支持现货和合约）
const getActionText = (action) => {
  const texts = {
    // 现货
    buy: '买入',
    sell: '卖出',
    // 合约
    open_long: '开多',
    open_short: '开空',
    close_long: '平多',
    close_short: '平空',
    close_position: '平仓'
  }
  return texts[action] || action
}

// 获取动作标签类型
const getActionTagType = (action) => {
  const types = {
    // 现货：买入=绿色，卖出=红色
    buy: 'success',
    sell: 'danger',
    // 合约：开多=绿色，开空=橙色，平多=蓝色，平空=紫色
    open_long: 'success',
    open_short: 'warning',
    close_long: '',
    close_short: 'info',
    close_position: 'danger'
  }
  return types[action] || 'info'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取币种列表（根据交易类型）
const fetchSymbols = async (tradeType = 'spot') => {
  symbolsLoading.value = true
  try {
    // 根据交易类型映射到 OKX 的 instType
    let instType = 'SPOT'  // 现货
    if (tradeType === 'swap') {
      instType = 'SWAP'  // 永续合约
    } else if (tradeType === 'futures') {
      instType = 'FUTURES'  // 交割合约
    }
    
    console.log(`📤 正在获取币种列表... (交易类型: ${tradeType}, instType: ${instType})`)
    const response = await getSymbols(instType)
    console.log('📥 币种数据:', response)
    
    if (response.code === '0' && response.data) {
      symbols.value = response.data
      console.log('✅ 币种列表加载成功，共', symbols.value.length, '个')
    } else {
      console.warn('⚠️ 币种数据格式异常')
      symbols.value = []
    }
  } catch (error) {
    console.error('❌ 获取币种列表失败:', error)
    ElMessage.warning('获取币种列表失败，请手动输入')
    symbols.value = []
  } finally {
    symbolsLoading.value = false
  }
}

// 监听交易类型变化，重新加载币种列表
watch(() => taskForm.value.strategy.trade_type, (newType, oldType) => {
  if (newType !== oldType) {
    console.log(`🔄 交易类型变化: ${oldType} -> ${newType}`)
    // 清空当前选择的币种
    taskForm.value.strategy.symbol = ''
    // 重新加载对应的币种列表
    fetchSymbols(newType)
  }
})

// 监听策略类型变化，自动调整条件
watch(() => taskForm.value.strategy.strategy_type, (newType, oldType) => {
  if (newType !== oldType && taskForm.value.conditions.length > 0) {
    // 切换策略类型时，重置条件
    if (newType === 'indicator') {
      // 切换到指标策略
      taskForm.value.conditions = [{
        indicator: 'rsi',
        relation: 'crossunder',
        value: 30,
        action: 'buy',
        trigger_interval_minutes: 10
      }]
    } else if (newType === 'zone') {
      // 切换到区间策略
      taskForm.value.conditions = [{
        indicator: 'price',
        relation: 'break_below_support',
        value: 0.01,
        action: 'buy',
        trigger_interval_minutes: 30
      }]
    }
  }
})

onMounted(() => {
  // 检查登录状态
  const userStr = localStorage.getItem('currentUser')
  if (userStr) {
    try {
      currentUser.value = JSON.parse(userStr)
      // 自动设置用户ID筛选
      filterForm.user_id = currentUser.value.id
    } catch (error) {
      console.error('解析用户信息失败:', error)
    }
  }
  
  // 如果未登录，跳转到登录页
  if (!currentUser.value) {
    window.location.href = '/login'
    return
  }
  
  fetchTasks()
  fetchSymbols()
})
</script>

<style scoped>
.task-manager {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  background: #fff;
}

.strategy-info {
  display: flex;
  gap: 12px;
  align-items: center;
  font-size: 13px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

.backtest-result {
  margin-top: 20px;
}

.profit {
  color: #67c23a;
  font-weight: bold;
}

.loss {
  color: #f56c6c;
  font-weight: bold;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sr-result {
  margin-top: 20px;
}

.sr-result h4 {
  margin-bottom: 10px;
  color: #303133;
}

.support-price {
  color: #67c23a;
  font-weight: bold;
}

.resistance-price {
  color: #f56c6c;
  font-weight: bold;
}
</style>

